package com.lebang.controller.sys.cences;

import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Login;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.CencesEarnDay;
import com.lebang.domain.TaskRouse;
import com.lebang.example.CencesEarnDayExample;
import com.lebang.model.MyConfig;
import com.lebang.model.TaskRouseModel;
import com.lebang.model.cences.CencesEarnApru;
import com.lebang.model.cences.TotalCount;
import com.lebang.service.DownAppService;
import com.lebang.service.NewRouseService;
import com.lebang.service.cences.CencesEarnDayService;
import com.lebang.service.sys.DictService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 新手任务
 *
 * @author hwq
 * @date 2020-02-06
 */
@Controller
@RequestMapping("/sys/cencesearnday")
public class CencesEarnDayController {
    @Autowired
    private CencesEarnDayService baseService;
    @Autowired
    private DownAppService downAppService;
    @Autowired
    private NewRouseService newRouseService;
    @Autowired
    private DictService dictService;
    @Value("#{'${check.sdkList}'.split(',')}")
    private List<String> sdkList;

    @Login
    @GetMapping("/list")
    public String list(Model model,HttpSession session) {
        List<TaskRouse> rouses = newRouseService.selectAll();
        rouses = newRouseService.checkRoot(rouses,session);
        model.addAttribute("item", rouses);
        String sdk = newRouseService.getFirstSdk(session,rouses);
        model.addAttribute("sdk", sdk);
        return "/cencesearnday/list";
    }

    @Login
    @GetMapping("/add")
    @DataSource("commonDB")
    public String add(Integer id, Model model) {
        CencesEarnDay vo;
        if (id != null) {
            vo = baseService.selectById(id);
        } else {
            vo = new CencesEarnDay();
        }
        model.addAttribute("item", vo);
        return "/cencesearnday/edit";
    }

    @Login
    @PostMapping("/edit")
    @ResponseBody
    @DataSource("commonDB")
    public JsonData edit(CencesEarnDay vo) {
        if (vo.getId() != null) {
            baseService.updateById(vo);
        } else {
            vo.setAppId(MyConfig.getEnv());
            baseService.insertModel(vo);
        }
        return Callback.success("success", "修改成功");
    }

    /**
     * @param page
     * @param limit
     * @param star
     * @param end
     * @param appStore
     * @param category 1新用户0老用户2全部
     * @return
     */
    @PostMapping("/page")
    @ResponseBody
    @Login
    public HashMap newlist(String likeBrand,Long page, Integer limit, Integer star, Integer end, String appStore, int category, int type, String sdkKey,HttpSession session) {
        // limit=limit-1;
        HashMap map = new HashMap(1);
        CencesEarnDayExample example = new CencesEarnDayExample();
        CencesEarnDayExample.Criteria c = example.createCriteria();
        example.setOffset((page - 1) * limit);
        example.setLimit(limit);
        example.setOrderByClause("time desc");
        if (star != null && end != null) {
            c.andTimeBetween(star, end);
        }
        if (!TextUtil.isEmpty(sdkKey)) {
            c.andSdkKeyEqualTo(sdkKey);
        } else {
            sdkKey = null;
        }
        if(!TextUtil.isEmpty(likeBrand)){
            c.andBrandLike(likeBrand+"%");
            appStore=null;
        }else {
            likeBrand=null;
            if (!TextUtil.isEmpty(appStore)) {
                c.andBrandEqualTo(appStore);
            }else {
                appStore=null;
            }
        }
        c.andAppIdEqualTo(MyConfig.getEnv());
        c.andTypeEqualTo(type);
        c.andCategoryEqualTo(category);
        if(newRouseService.isRoot(session)){
                c.andSdkKeyNotIn(sdkList);
        }
        map.put("count", baseService.countEarnDay(example));
        map.put("code", 0);
        List<CencesEarnDay> masters = baseService.selectEarnDay(example);
        CencesEarnDay vo = baseService.sumData(star, end, appStore, category, type, sdkKey,likeBrand,MyConfig.getEnv());
        if (null != vo) {
            vo.setTime(-1);
            masters.add(vo);
        }
        map.put("data", masters);
        return map;
    }

    @Login
    @PostMapping("/lastCheck")
    @ResponseBody
    public String cen(String date) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate end = LocalDate.parse(date, fmt);
        baseService.starDataInit(LocalDateTime.of(end.plusDays(1), LocalTime.MIN));
        return "success";
    }

    @Login
    @PostMapping("/delete")
    @ResponseBody
    @DataSource("commonDB")
    public JsonData delete(Integer id) {

        baseService.deleteByTime(baseService.selectById(id).getTime());
        return Callback.success("success", "删除成功");
    }

    @Login
    @PostMapping("/sumcount")
    @ResponseBody
    public JSONObject sumcount(Integer id,
                               @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime star,
                               @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end,


                               String appStore) {
        JSONObject jsonObject = new JSONObject();
        List<TotalCount> list = new ArrayList<>();
        LocalDateTime dateTime = LocalDateTime.of(2020, 3, 24, 0, 0, 0, 0);

        int between = end.getDayOfYear() - star.getDayOfYear();
        if (TextUtil.isEmpty(appStore)) {
            appStore = null;
        }
        //最大次数
        int count = dictService.selectIntByKeyName("csj_down_success_count") + dictService.selectIntByKeyName("csj__look_success_count") + 7;

        for (int i = 1; i < count; i++) {
            TotalCount totalCount = baseService.selectData(star, end, appStore, i, between);
            list.add(totalCount);
        }

        // List<TaskRouseModel>
        jsonObject.put("code", 0);
        jsonObject.put("data", list);
        jsonObject.put("count", list.size());
        return jsonObject;
    }

    @Login
    @PostMapping("/sumcountv2")
    @ResponseBody
    public JSONObject sumcountv2(Integer id,
                                 @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime star,
                                 @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end,


                                 String appStore) {
        JSONObject jsonObject = new JSONObject();
        List<TaskRouseModel> list = new ArrayList<>();
        LocalDateTime dateTime = LocalDateTime.of(2020, 3, 24, 0, 0, 0, 0);

        int between = end.getDayOfYear() - star.getDayOfYear();
        if (TextUtil.isEmpty(appStore)) {
            appStore = null;
        }

        List<TaskRouse> rouses = newRouseService.selectAll();
        String finalAppStore = appStore;
        rouses.forEach(s -> {
            TaskRouseModel totalCount = baseService.selectDatav2(star, end, finalAppStore, s, between);
            list.add(totalCount);
        });

        jsonObject.put("code", 0);
        jsonObject.put("data", list);
        jsonObject.put("count", list.size());
        // List<TaskRouseModel>
        return jsonObject;
    }

    @Login
    @GetMapping("/apru")
    public String apru(Model model,HttpSession session) {
        List<TaskRouse> rouses = newRouseService.selectAll();
        rouses = newRouseService.checkRoot(rouses,session);
        model.addAttribute("item", rouses);
        return "/cencesearnday/data";
    }

    @Login
    @PostMapping("/apru")
    @ResponseBody
    @DataSource("commonDB")
    public JSONObject apru(HttpServletRequest request, String sdkKey, Integer type, Integer star, Integer end, Integer category, String appStore) {
        JSONObject jsonObject = new JSONObject();
        List<CencesEarnApru> apru = new ArrayList<>();
        CencesEarnDayExample example = new CencesEarnDayExample();
        example.setOrderByClause("time desc");
        CencesEarnDayExample.Criteria c = example.createCriteria();
        if (star != null && end != null) {
            c.andTimeBetween(star, end);
        }
        if (!TextUtil.isEmpty(sdkKey)) {
            c.andSdkKeyEqualTo(sdkKey);
        }

        c.andBrandNotEqualTo("all");

        c.andTypeEqualTo(type);
        c.andCategoryEqualTo(category);
        c.andAppIdEqualTo(MyConfig.getEnv());
        List<CencesEarnDay> masters = baseService.selectByExample(example);
        masters.forEach(s -> {
            if (s.getBrand().startsWith("csj")) {
                s.setBrand("csj");
            }
            if (s.getBrand().startsWith("gdt")) {
                s.setBrand("gdt");
            }
        });
        Map<Integer, List<CencesEarnDay>> data = masters.stream().collect(Collectors.groupingBy(CencesEarnDay::getTime));
        data.forEach((key, value) -> {
            CencesEarnApru apru1 = new CencesEarnApru(key.toString(), value);
            apru.add(apru1);
        });
        jsonObject.put("code", 0);
        jsonObject.put("data", apru.stream()
                .sorted(Comparator.comparing(CencesEarnApru::getTime).reversed()).collect(Collectors.toList()));
        jsonObject.put("count", apru.size());
        return jsonObject;
    }

}
